//
//  WebServiceManager.m
//  eGiftr
//
//  Created by Phien Tram on 9/3/13.
//  Copyright (c) 2013 eGiftr. All rights reserved.
//

#import "WebServiceManager.h"
#import "SBJson.h"
#import "NSDictionary+Utility.h"

const NSString *apiGatewayURL = @"http://65.111.178.188";

@interface WebServiceManager ()
{
    BOOL loadingData;
}

@property (nonatomic, strong) NSString *serviceName;
@property (nonatomic, strong) NSString *method;
@property (nonatomic, strong) NSDictionary *inputData;


@end

@implementation WebServiceManager

- (id)initWithData:(NSDictionary *)data serviceName:(NSString *)serviceName method:(NSString *)method
{
    self = [super init];
    if (self) {
        _inputData = data;
        _serviceName = serviceName;
        _method = method;
    }
    return self;
}

- (void)request
{
    if (loadingData) {
        return;
    }
    loadingData = YES;
	
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    NSURLRequest *theRequest = [self createConnectionURLRequest];
    if (theRequest) {
        self.connection = [NSURLConnection connectionWithRequest:theRequest delegate:self];
        if (self.connection) {
            self.receivedData = [NSMutableData data];
        } else {
            loadingData = NO;
        }
    }
}

- (void)cancelRequest
{
    if (loadingData)
    {
        [self.connection cancel];
        loadingData = NO;
        
        self.receivedData = nil;
        self.connection = nil;
    }
}

- (NSString *)URL
{
    NSString *uri = @"";
    if ([_method isEqual:@"GET"])
    {
        uri = [NSString stringWithFormat:@"%@/%@?%@", apiGatewayURL, _serviceName, [self.inputData parameterize]];
    }
    else
    {
        uri = [NSString stringWithFormat:@"%@/%@", apiGatewayURL, _serviceName];
    }
    return uri;
}

- (NSMutableURLRequest *)createConnectionURLRequest
{
    NSString * urlString = [self URL];
    NSLog(@"URL = %@", urlString);
    if ([urlString length] > 0) {
        urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:urlString];
        NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:120.0];
        [theRequest setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        if ([_method isEqual:@"POST"]) {
            [theRequest setHTTPMethod:@"POST"];
            NSData *data = [[_inputData JSONRepresentation] dataUsingEncoding:NSUTF8StringEncoding];
            [theRequest setHTTPBody:data];
        }
        return theRequest;
    }
    
    return nil;
}

- (BOOL)parse:(NSString **)error code:(NSInteger *)code
{
    id jResult = [self.receivedData JSONValue];
    BOOL success = [[jResult objectForKey:@"Success"] boolValue];
    if (success)
    {
        error = nil;
        self.result = jResult;
    }
    else
    {
        NSString *message = [jResult objectOrNilForKey:@"errorMessage"];
        if (message) {
            *error = message;
        }
        NSNumber *errorCode = [jResult objectOrNilForKey:@"errorCode"];
        *code = [errorCode integerValue];
        self.result = nil;
        return NO;
    }
    
    return YES;
}

#pragma mark -
#pragma mark NSURLConnection delegate

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[self.receivedData appendData:data];
}

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	loadingData = NO;
	self.receivedData = nil;
	self.connection = nil;
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    
	if ([_delegate respondsToSelector:@selector(webServiceManagerFinishGetData:error::)])
	{
		[_delegate webServiceManagerFinishGetData:self error:error];
	}
}

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [self.receivedData setLength:0];
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
	loadingData = NO;
	self.connection = nil;
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    
	NSError *error = nil;
    NSString *errorString = nil;
    NSInteger errorCode = -1;
    if ([_delegate respondsToSelector:@selector(webServiewManagerBeforeParsingData:data:)]) {
        [_delegate webServiewManagerBeforeParsingData:self data:self.receivedData];
    }
    
    BOOL success = [self parse:&errorString code:&errorCode]; //perform parsing receivedData before clear
    if (!success) {
        NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
        if (errorString == nil) {
            errorString = @"General Error";
        }
        [userInfo setObject:errorString forKey:NSLocalizedDescriptionKey];
        error = [NSError errorWithDomain:NSCocoaErrorDomain code:errorCode userInfo:userInfo];
    }
    
	self.receivedData = nil;
	
	//notify after parsed
    if ([_delegate respondsToSelector:@selector(webServiceManagerFinishGetData:error:)])
	{
		[_delegate webServiceManagerFinishGetData:self error:error];
	}
}

@end
